package io.github.idol.roomlist.room

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import io.github.idol.Constants
import io.github.idol.R
import io.github.idol.databinding.ActivityRoomDetailBinding
import io.github.idol.utils.InjectorUtils

class RoomDetailActivity : AppCompatActivity() {

    private lateinit var roomDetailViewModel: RoomDetailViewModel
    private lateinit var binding:ActivityRoomDetailBinding
    private var isFirstIn = true
    private var isLoadMore = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_detail)

        binding = DataBindingUtil.setContentView(this,R.layout.activity_room_detail)
        val roomDetailAdapter = RoomDetailAdapter(RoomDetailDiffCallback())
        binding.rvRoomDetail.adapter = roomDetailAdapter

        binding.rvRoomDetail.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
        binding.rvRoomDetail.addOnScrollListener(object:RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    if((recyclerView!!.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()==0){
                        if(!isLoadMore){
                            isLoadMore = true
                            roomDetailViewModel.getRoomDetail()
                        }
                    }
                }
            }
        })

        roomDetailViewModel = InjectorUtils.provideLoginViewModelFactory(application).create(RoomDetailViewModel::class.java)
        roomDetailViewModel.roomId = intent.getIntExtra(Constants.ROOM_ID,0)
        roomDetailViewModel.lastTime = 0L
        roomDetailViewModel.getRoomDetailData().observe(this, Observer {
            isLoadMore = false;
            if(isFirstIn){
                binding.rvRoomDetail.smoothScrollToPosition(it!!.size-1)
                isFirstIn = false
            }
            roomDetailAdapter.submitList(it)
        })

        isLoadMore = true
        roomDetailViewModel.getRoomDetail()
    }

    companion object {
        fun startRoomListActivity(activity: Activity,roomId:Int){
            val intent = Intent(activity,RoomDetailActivity::class.java)
            intent.putExtra(Constants.ROOM_ID,roomId)
            activity.startActivity(intent)
        }
    }
}
